from selenium import webdriver
from configparser import ConfigParser
from selenium.webdriver.common.by import By
from selenium.common import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

cfg = ConfigParser()
r = cfg.read("data.ini")
username = cfg.get("username", "username")
password = cfg.get("password", "password")


class Login_Text(object):
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.get("https://www.17k.com/")
        self.wait = WebDriverWait(self.driver, 10)

    def search(self):
        try:
            self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="header_login_user"]/a[1]'))).click()
            login_ifram = self.wait.until(
                EC.presence_of_element_located((By.XPATH, '/html/body/div[20]/div/div[1]/iframe')))
            self.driver.switch_to.frame(login_ifram)

            # 输入账号密码
            self.wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/from/dl/dd[2]/input'))).send_keys(
                username)
            self.wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/form/dl/dd[2]/input'))).send_keys(
                password)

            # 点击同意协议
            self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="protocol"]'))).click()
            time.sleep(5)
            self.wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/form/dl/dd[5]/input'))).click()

        except TimeoutException:
            return self.search()


if __name__ == '__main__':
    spider = Login_Text()
    spider.search()
